var dtLanguageCn={
	paginate : {
		first : '首页',
		last : '末页',
		previous : '上一页',
		next : '下一页'
	},
	lengthMenu : '显示 _MENU_ 条',
	zeroRecords : '没有检索到有效数据！',
	info : '显示 _START_ 到 _END_ 条记录，共计 _TOTAL_ 条记录',
	infoEmpty : '没有检索到有效数据！',
	search : '查找：',
	processing : '正在加载数据，请稍候...',
	infoFiltered : '共计 _TOTAL_ 条记录',
	select : {rows :'选中%d条记录'}
};
(function($) {
	$.fn.autoDataTable = function(options) {
		var setting = {
			tableId : null,
			columns : [],
			columnDefs : [],
			getParams : null,
			dealPostData : null,
			fnInitComplete : null,
			fnDrawCallback : null,
			iLeftColumns : null,
			order : null,
			scroll : true,
			dbcShow:true,
			title : "",
			controller : null,
			id : "id",
			queryForm : "auto-query-form",
			dataForm : "auto-data-form",
			showForm : "auto-show-form"
		};
		setting.tableId = $(this).attr("id");
		setting = $.extend(setting, options);
		var $this=$(this);
		var _dataTable = null;
		
		function getFilter(aoData) {// 查询过滤参数
			var datas = null;
			if (typeof (setting.getParams) == 'function') {
				datas = setting.getParams.call(this);
			} else {
				var $queryForm = $("#" + setting.queryForm);
				if ($queryForm.length > 0) {
					datas = $queryForm.serializeObject();
					// debugger
				} else {
					datas = {};
				}
			}
			if (!_.isEmpty(aoData)) {
				datas['dtJson'] = JSON.stringify(aoData);
			}
			return datas;
		};
		function getOrder() {// 排序字段
			var order = [];
			if (setting.order != null) {
				order.push(setting.order);
			}
			return order;
		};

		function getSelectedRow() {
			var rows = [];
			if (null != _dataTable) {
				$("#" + setting.tableId + " tr.selected").each(function() {
					rows.push(_dataTable.fnGetData(this));
				});
			}
			return rows;
		};

		var tableOpts = {
			'ajax' : {
				dataType : 'json',
				traditional : true,
				type : 'post',
				url : setting.controller + "/list",
				data : function(aoData) {
					return getFilter(aoData);
				},
				error : function(resp) {
					showMsg("数据加载失败！", "error");
					waitLoading(false);
					//console.log(JSON.stringify(resp));
				}
			},
			serverSide : true,// 是否开启服务器模式
			stateSave : false,// 保存状态 - 在页面重新加载的时候恢复状态（页码等内容）
			processing : true,// 当表格处在处理过程（例如排序）中时，启用或者禁止'processing'指示器的显示。
			responsive : true,// 自动适应屏幕
			displayStart : 0,// 初始化显示的时候从第几条数据开始显示(一开始显示第几页)
			columns : setting.columns,
			columnDefs : setting.columnDefs,
			language : dtLanguageCn,
			pagingType : 'simple_numbers',
			pageLength : 10,
			searching : false,
			bLengthChange : false,
			bAutoWidth : true,
			order : getOrder(),
			fnInitComplete : function(oSettings, json) {
				if (typeof (setting.fnInitComplete) == 'function') {
					setting.fnInitComplete.call(oSettings);
					return;
				}
				$("#" + oSettings.sTableId + " tbody").on("click", "tr", function() {
							$(this).toggleClass("selected");
						}).on( "dblclick", "tr", function(e) {
							if(!setting.dbcShow)return;
							var $row = $("#" + setting.tableId).dataTable() .fnGetData(this);
							var url = setting.controller + "/get/" + $row[setting.id];
							var buttons = [];
							if($("#del_btn[data-uri*='"+setting.controller+"']").length>0){//有删除按钮，说明有删除权限，不准确
								buttons.push({
									label : '删除',
									cssClass : 'btn-danger btn-sm',
									icon : 'fa fa-trash',
									action : function(dialog) {
										confirmDialog("<strong class='text-danger'>确定删除选中" + setting.title + "记录吗？</strong>", function() {
											var delurl = setting.controller + "/delete/" +$row[setting.id];
											postData(delurl, null,null, function(data) {
												if (data.success) {
													dialog.close();
													_dataTable.fnDraw();
												}
											});
										});
									}
								});
							};
							buttons.push({
								label : '打印',
								cssClass : 'btn-success btn-sm',
								icon : 'fa fa-print',
								action : function(dialog) {
									var printWarp = $(dialog.getModalBody()).find("form#"+setting.showForm);
									if(printWarp.length < 1){
										printWarp = $(dialog.getModalBody()).find(".printArea");
									}
									printWarp.printArea({extraCss: "assets/plugin/printArea/PrintArea.css"});
								}
							});
							buttons.push({
								label : '关闭',
								cssClass : 'btn-info btn-sm',
								icon : 'fa fa-window-close',
								action : function(dialog) {
									dialog.close();
								}
							});
							var dialog = loadUriDialog("查看" + setting.title, url, null, $this.data("form-width"), null,
									buttons, function(dialog) {

									});
							//console.log("db ckick open detail");
						});
			},
			fnPreDrawCallback : function() {
				// console.log("fnPreDrawCallback");
				// waitLoading(true);
			},
			fnDrawCallback : function(oSettings, json) {
				// console.log("fnDrawCallback");
				if (typeof (setting.fnDrawCallback) == 'function') {
					setting.fnDrawCallback.call(this, oSettings, json);
				}
				waitLoading(false);
			}
		};
		if (setting.scroll) {// 是否有滚动条
			tableOpts.sScrollX = "100%";
			tableOpts.bScrollCollapse = true;
		}

		//
		try {
			_dataTable = $(this).dataTable(tableOpts);
			if (typeof (setting.iLeftColumns) == "number") {
				new $.fn.dataTable.FixedColumns(_dataTable, {iLeftColumns : setting.iLeftColumns});
			}
			// 查询所有数据
			$("#query_btn").click(function(e) {// 查询按钮
				e.preventDefault();// 传入的查询条件
				_dataTable.fnDraw();
			});

			// 新增、编辑行数据
			$("#add_btn,#edit_btn").click(function(e) {
				e.preventDefault();
				var url = setting.controller + "/form/";
				var tip = "新增" + setting.title;
				if ("edit_btn" == $(this).attr("id")) {// 编辑
					var rows = getSelectedRow()
					if (null == rows || rows.length < 1) {
						showMsg("请单击选择数据行！", "error");
						return;
					} else if (rows.length > 1) {
						showMsg("编辑数据时，只能选择一条记录！", "error");
						return;
					}
					url += rows[0][setting.id];// 获取当前选中行ID
					tip = "更新" + setting.title;
				}
				var buttons = [ {
					label : '保存',
					cssClass : 'btn-success btn-sm',
					icon : 'fa fa-check-square',
					action : function(dialog) {
						postValidatorForm("auto-data-form", function(data) {
							if (data.success) {
								_dataTable.fnDraw();
								closeDialog();
							}
						});
					}
				}, {
					label : '取消',
					cssClass : 'btn-info btn-sm',
					icon : 'fa fa-window-close',
					action : function(dialog) {
						dialog.close();
					}
				} ];
				loadUriDialog(tip, url, null, $this.data("form-width"),null, buttons, function(dialog) {
					//$(dialog.getModalBody()).find("form.bv-form").attr("data-bv-message","表单数据验证失败").bootstrapValidator();
				});
			});
			// 删除数据
			$('#del_btn').click(
					function(e) {
						e.preventDefault();
						var rows = getSelectedRow()
						if (null == rows || rows.length < 1) {
							showMsg("请单击选择数据行！", "error");
							return;
						}
						confirmDialog("<strong class='text-danger'>确定删除选中的" + rows.length + "条" + setting.title + "记录吗？</strong>", function() {
							var ids = "";// 获取当前选中行ID
							for (var i = 0; i < rows.length; i++) {
								if ("" != ids){ids += "-";}
								ids += rows[i][setting.id];
							}
							var url = setting.controller + "/delete/" + ids;
							postData(url, null,null, function(data) {
								if (data.success) {
									_dataTable.fnDraw();
								}
							});
						});
					});
		} catch (e) {
			showMsg("数据加载失败，" + e.message, "error");
			waitLoading(false);
		}
		return _dataTable;
	}
})(window.jQuery);